#
# pH - Web Development Framework
#
# 
#

require 'socket'
require 'webrick/httpserver'
require 'webrick/httpresponse'
require 'cgi'

require 'ph/core/status'

module Ph
  
	#
	# Handles a user request.
	#
  class Session
    
    attr_reader :application, :request
    attr_reader :header, :response
    attr_reader :get, :post
    attr_reader :action
    
    def initialize(application, socket)
      @application = application
      @socket = socket
      @response = WEBrick::HTTPResponse.new({:HTTPVersion => '1.1'})
      
      @request = WEBrick::HTTPRequest.new({})
      @request.parse(socket)
      
      @status = Ph::Status.new(self)
      
      @get = if @request.query_string then CGI::parse(@request.query_string) else Hash.new end
      @post = if @request.body then @post = CGI::parse(@request.body) else Hash.new end
      
      if @get.has_key? 'action' then
        @action = @get['action'][0]
      elsif @post.has_key? 'action' then
        @action = @post['action'][0]
      end 

      self.log "#{request.request_method} #{request.path}"
    end
    
    
    # Handles socket output and makes sure headers are outputted correctly
    def << (what)
      @response.body << what
      return self
    end
    
    def output
      @socket.print @response
    end
    
    def close
      return if @socket.closed?
			self.output
      @socket.close
    end
    
    def log(msg)
      @application.logger.log "[#{request.peeraddr[2]}:#{request.peeraddr[3]}] " + msg
    end
    
  end
end
